import React, { useState } from 'react';
import { CopyOutlined, UserOutlined, RobotOutlined } from '@ant-design/icons';
import { message as antdMessage } from 'antd';
import TypeWriter from './TypeWriter';
import './MessageItem.css';

const MessageItem = ({ message, isLast, onTypingComplete }) => {
    const [messageApi, contextHolder] = antdMessage.useMessage();
    const [showCopy, setShowCopy] = useState(false);

    const handleCopy = async () => {
        try {
            await navigator.clipboard.writeText(message.content);
            messageApi.success('已复制到剪贴板');
        } catch (error) {
            messageApi.error('复制失败');
        }
    };

    const formatTime = (timestamp) => {
        return new Date(timestamp).toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    const renderContent = () => {
        if (message.role === 'assistant' && message.isStreaming && !message.isComplete) {
            // 流式输出中，使用TypeWriter逐字显示
            return (
                <div className="message-content-wrapper">
                    <TypeWriter
                        text={message.content}
                        speed={45} // 45ms一个字符
                        showCursor={true}
                        shouldStart={message.shouldStartTyping} // 使用新的触发机制
                        onComplete={() => {
                            console.log('打字完成');
                            // 通知父组件打字完成
                            if (onTypingComplete) {
                                onTypingComplete(message.id);
                            }
                        }}
                    />
                </div>
            );
        } else {
            // 完成的消息，直接显示
            return (
                <div className="message-content-wrapper">
                    {message.isTemplate ? (
                        // 模板消息使用特殊渲染
                        <div className="template-message" dangerouslySetInnerHTML={{
                            __html: message.content
                                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                                .replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
                                .replace(/`(.*?)`/g, '<code>$1</code>')
                                .replace(/\n/g, '<br/>')
                        }} />
                    ) : (
                        // 普通消息
                        <div className="normal-message">
                            {message.content}
                        </div>
                    )}
                </div>
            );
        }
    };

    return (
        <div className={`message-item ${message.role}`}>
            {contextHolder}
            
            <div className="message-wrapper">
                {/* 头像 */}
                <div className="message-avatar">
                    {message.role === 'user' ? (
                        <UserOutlined className="avatar-icon user-avatar" />
                    ) : (
                        <RobotOutlined className="avatar-icon assistant-avatar" />
                    )}
                </div>

                {/* 消息内容 */}
                <div className="message-content-container">
                    <div className="message-header">
                        <span className="message-role">
                            {message.role === 'user' ? '你' : 'AI助手'}
                        </span>
                        <span className="message-time">
                            {formatTime(message.timestamp)}
                        </span>
                    </div>

                    <div 
                        className={`message-content ${message.isError ? 'error' : ''}`}
                        onMouseEnter={() => setShowCopy(true)}
                        onMouseLeave={() => setShowCopy(false)}
                    >
                        {renderContent()}
                        
                        {/* 复制按钮 */}
                        {showCopy && message.content && message.role === 'assistant' && (
                            <button 
                                className="copy-button"
                                onClick={handleCopy}
                                title="复制消息"
                            >
                                <CopyOutlined />
                            </button>
                        )}
                    </div>

                    {/* 加载状态 */}
                    {message.isStreaming && !message.isComplete && (
                        <div className="loading-indicator">
                            <div className="loading-dots">
                                <span></span>
                                <span></span>
                                <span></span>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

export default MessageItem;
